<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-select
        v-model="listQuery.shopName"
        :disabled="this.$route.query.shopId"
        clearable
        style="width: 200px"
        class="filter-item"
        placeholder="请选择项目"
        @change="selectProductType"

      >
        <el-option v-for="(item,index) in shopList" :key="index" :label="item.shopName" :value="{ value: item.id, label: item.shopName}" />
      </el-select>
      <el-button v-permission="['admin:log:list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['admin:log:create']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
      <el-button v-permission="['admin:log:create']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleBu">补日志</el-button>

    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
    >

      <el-table-column align="center" type="selection" width="55" />

      <el-table-column align="center" label="ID" prop="id" />

      <el-table-column align="center" min-width="100" label="日期" prop="gmt_day">
        <template slot-scope="scope"><el-col>{{ scope.row.gmt_day | formatDate }}</el-col></template>

      </el-table-column>

      <el-table-column
        align="center"
        max-width="300"
        min-width="300"
        label="描述"
        prop="description"
      />
      <el-table-column align="center" min-width="100" label="操作人" prop="realName" />

      <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">

          <el-button v-permission="['admin:log:edit']" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <!--        <el-button v-permission="['admin:log:delete']" type="danger" style="margin:5px" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        -->
          <!--
          <el-button style="margin:5px" size="mini" @click="toShopOne(scope.row)">一镇一品</el-button>
-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-tooltip placement="top" content="返回顶部">
      <back-to-top :visibility-height="100" />
    </el-tooltip>
  </div>
</template>

<script>
import { listGoods, deleteGoods, detailGoods, batchDeleteGoods, statistics } from '@/api/log'
import BackToTop from '@/components/BackToTop'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { selectShop } from '@/api/frontutil'

export default {
  name: 'GoodsList',
  components: { BackToTop, Pagination },
  data() {
    return {
      shopList: [],
      list: [],
      total: 0,
      goodsStatisticsCheckList: [40, 50, 70],
      listLoading: true,
      categoryOptions: [],
      goodsStatusMap: [{ value: 0, name: '下架' }, { value: 1, name: '正常' }],
      listQuery: {
        page: 1,
        type: 2,
        limit: 20,
        title: undefined,
        status: undefined,
        barcode: undefined,
        categoryId: undefined,
        shopId: this.$route.query.shopId,
        shopName: this.$route.query.shopName

      },
      goodsDetail: '',
      detailDialogVisible: false,
      selectedIds: [],
      goodsStatisticsDialogVisible: false,
      goodsStatisticsTimePickModel: {}
    }
  },
  created() {
    this.getList()
    this.listShop()
    this.refreshCategoryOptions()
  },
  methods: {
    listShop() {
      selectShop()
        .then(response => {
          this.shopList = response.data.data
        })
        .catch(() => {
        })
    },
    selectProductType(data) {
      const { value, label } = data
      this.listQuery.shopName = label
      this.listQuery.shopId = value
    },
    formatDate(row, column) {
      // 获取单元格数据
      const data = row[column.property]
      if (data == null) {
        return null
      }
      const dt = new Date(data)
      return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate() + ' ' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds()
    },
    getList() {
      this.listLoading = true
      listGoods(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleCreate() {
      var url = '/shopone/logupsert'
      if (this.$route.query.shopId) {
        url = url + '?shopId=' + this.$route.query.shopId + '&shopName=' + this.$route.query.shopName
      }
      this.$router.push({ path: url })
    },
    handleBu() {
      var url = '/shopone/logupsert?isBu=1'
      if (this.$route.query.shopId) {
        url = url + '&shopId=' + this.$route.query.shopId + '&shopName=' + this.$route.query.shopName
      }
      this.$router.push({ path: url })
    },

    handleUpdate(row) {
      var url = '/shopone/logupsert'
      if (this.$route.query.shopId) {
        url = url + '?shopId=' + this.$route.query.shopId + '&shopName=' + this.$route.query.shopName
      }
      this.$router.push({ path: url, query: { id: row.id }})
    },
    showDetail(row) {
      if (!this.detailDialogVisible) {
        detailGoods(row.id)
          .then(response => {
            this.goodsDetail = response.data.data.detail.replace(/<img/g, "<img style='max-width:100%;height:auto;line-height:0px'")
            this.detailDialogVisible = true
          })
      }
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除产品--' + row.title + '--, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteGoods(row.id)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        return false
      })
    },
    handleSelectionChange(e) {
      const temp = []
      e.forEach(item => {
        temp.push(item.id)
      })
      this.selectedIds = temp
    },
    handleBatchDelete(e) {
      // 执行批量删除
      this.$confirm('此操作将永久删除选中的' + this.selectedIds.length + '件产品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        batchDeleteGoods(this.selectedIds)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            this.getList()
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        return false
      })
    },
    showGoodsStatistics() {
      // 展示产品统计
      this.goodsStatisticsDialogVisible = true
      this.goodsStatisticsTimePickModel = {}
      this.goodsStatisticsCheckList = [40, 50, 70]
    },
    handleGoodsStatistics() {
      if (this.goodsStatisticsCheckList.length === 0) {
        this.$notify.error({
          title: '失败',
          message: '至少选择一种状态'
        })
      }
      // 构件请求参数
      const param = {}
      if (this.goodsStatisticsTimePickModel.length > 1) {
        // 若存在时间
        param['gmtStart'] = this.goodsStatisticsTimePickModel[0].getTime()
        param['gmtEnd'] = this.goodsStatisticsTimePickModel[1].getTime()
      }
      statistics(this.goodsStatisticsCheckList, this.selectedIds, param)
        .then(res => {
          res.data.data.forEach(item => {
            item.totalPrice = item.totalPrice / 100.0
            item.confirmPrice = item.confirmPrice / 100.0
            item.refundPrice = item.refundPrice / 100.0
          })
          this.handleDownload(res.data.data)
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
    },
    handleDownload(data) {
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          'SPU_ID',
          'SPU标题',
          'SKU_ID',
          'SKU标题',
          '数量',
          '总金额',
          '确认金额',
          '退款金额'
        ]
        const filterVal = [
          'spuId',
          'spuTitle',
          'skuId',
          'skuTitle',
          'num',
          'totalPrice',
          'confirmPrice',
          'refundPrice'
        ]
        excel.export_json_to_excel2(tHeader, data, filterVal, '产品信息')
      })
    }
  }
}
</script>
